# -*- coding: utf-8 -*-
"""
    :copyright: (c) 2019 by enjoyZHou on 2019-06-28
"""
import json
import os
import sys
import getopt
from .xls_extract import extract_file
from .scrapy_extract import start_crawl
from .download import download


def extract_file_download(i_file=None, o_dir=None, crawl=None, x_range=None):
    """
    分析下载文件
    :param i_file:规则文件
    :param o_dir:保存目录
    :param crawl: 爬虫工具
    :param x_range: 范围 [1,100]
    :return:
    """

    if not i_file:
        return False, None, u'规则文件不存在'
    if not os.path.isfile(i_file):
        return False, None, u'规则文件不存在'
    file_dir, full_filename = os.path.split(i_file)
    filename, extension = os.path.splitext(full_filename)
    o_dir = o_dir or os.path.join(file_dir, str(filename))
    print('目标规则文件为：', i_file)

    # 表格文件
    if extension in ('.xls', '.xlsx'):
        url_list = extract_file(i_file)
    elif crawl and extension in ('.json',):
        with open(i_file, 'r') as f:
            conf = f.read()
            try:
                conf = json.loads(conf)
            except:
                return False, None, u'不标准的json格式'
            url_list = start_crawl(conf, x_range=x_range)
    else:
        if crawl:
            return False, None, u'规则文件格式不被支持，已支持文件类型：json'
        return False, None, u'规则文件格式不被支持，已支持文件类型：xls,xlsx'

    if not o_dir:
        o_dir = 'QSDownload'

    print('保存目录：', o_dir)

    # 开始下载
    download(url_list, o_dir)
    return True, None, u'ok'


def main(args=None):
    argv = None
    if args is None:
        argv = sys.argv[1:]
    if not argv:
        sys.stderr.write('ERROR: %s' % '参数未填写')
        sys.stderr.write(os.linesep)
        sys.exit(1)
    help = 'qsdnd -i <inputfile> -o <outputdir> -c <usecrawl>'
    try:
        opts, args = getopt.getopt(argv, 'hi:o:c:r:', ['ifile=', 'odir=', 'crawl=', 'range='])
    except getopt.GetoptError:
        sys.stderr.write(help)
        sys.stderr.write(os.linesep)
        sys.exit(2)
    input_file = output_dir = crawl = x_range = None
    # 取出参数
    for opt, arg in opts:
        if opt == '-h':
            sys.stderr.write(help)
            sys.stderr.write(os.linesep)
            sys.exit()
        elif opt in ('-i', '--ifile'):
            input_file = arg
        elif opt in ('-o', '--odir'):
            output_dir = arg
        elif opt in ('-c', '--crawl'):
            crawl = arg
        elif opt in ('-r', '--range'):
            x_range = arg and arg.split('-')

    is_ok, data, err = extract_file_download(input_file, output_dir, crawl, x_range)
    if not is_ok:
        sys.stderr.write('ERROR: %s' % err)
        sys.stderr.write(os.linesep)
        sys.exit(2)
